#include "../../Header/Entities/Image2D.h"

GLuint Image2D::Init()
{
	LOGI("Init data\n");
	//Vertex define
	Vertex vertices[4];
	vertices[0].Posotion = Vector3(-1.0f, -1.0f, 0.0f);
	vertices[1].Posotion = Vector3(-1.0f, 1.0f, 0.0f);
	vertices[2].Posotion = Vector3(1.0f, -1.0f, 0.0f);
	vertices[3].Posotion = Vector3(1.0f, 1.0f, 0.0f);

	vertices[0].UV = Vector2(0.0f, 0.0f);
	vertices[1].UV = Vector2(0.0f, 1.0f);
	vertices[2].UV = Vector2(1.0f, 0.0f);
	vertices[3].UV = Vector2(1.0f, 1.0f);

	GLushort indices[6] = { 0, 1, 2, 2, 3, 1 };

	m_Mesh = new ObjectMesh();
	m_Mesh->BindData(vertices, 4, indices, 6);

	//Texture define
	m_Texture = new ObjectTexture();

	//char** strSrcs = String::NewStringArray(1, "../Resources/Textures/Dirt.tga");
	//m_Texture->Init(GL_TEXTURE_2D, 1, strSrcs);


	//Shader define
	char gVertexShader[] =
		"attribute vec3 a_PosL;"
		"attribute vec4 a_Color;"
		"attribute vec2 a_UV;"
		"varying vec4 v_Color;"
		"varying vec2 v_UV;"
		"void main() {"
		"	vec4 PosW = vec4(a_PosL, 1.0);"
		"	gl_Position = PosW;"
		"	"
		"	v_Color = a_Color;"
		"	v_UV = a_UV;"
		"}";

	char gFragmentShader[] =
		"precision mediump float;"
		"uniform bool u_GrayScale;"
		"varying vec4 v_Color;"
		"varying vec2 v_UV;"
		""
		"void main()"
		"{"
		"	vec4 Color = vec4(0.0, 1.0, 0.0, 1.0);"
		"	if (u_GrayScale)"
		"		Color = vec4(0.5, 0.5, 0.5, 1.0);"
		"	gl_FragColor = Color;"
		"}";

	m_Shader = new ObjectShader();
	m_Shader->InitFormSRC(gVertexShader, gFragmentShader);
	//m_Shader->InitFormFile("../Resources/Shaders/temp.vsh", "../Resources/Shaders/temp.fsh");
	return 0;
}

void Image2D::Update(float)
{

}

void Image2D::Draw()
{
	glUseProgram(m_Shader->m_Program);

	//Bind vertex data
	glBindBuffer(GL_ARRAY_BUFFER, m_Mesh->GetVBO());
	if (m_Shader->m_Position != -1)
	{
		glEnableVertexAttribArray(m_Shader->m_Position);
		glVertexAttribPointer(m_Shader->m_Position, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if (m_Shader->m_UV != -1)
	{
		glEnableVertexAttribArray(m_Shader->m_UV);
		glVertexAttribPointer(m_Shader->m_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3) + sizeof(Vector4));
	}

	//Bind grayscale
	if (m_Shader->m_GrayScaleOption != -1)
	{
		glUniform1i(m_Shader->m_GrayScaleOption, m_IsSelected);
	}

	//Bind vertex index
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Mesh->GetIBO());

	//m_Texture->Bind(*m_Shader);

	//draw
	glDrawElements(GL_TRIANGLES, m_Mesh->GetIBOSize(), GL_UNSIGNED_SHORT, 0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	//m_Texture->UnBind();
}

void Image2D::Destroy()
{
	//m_Mesh->Destroy();
	SAFE_DEL(m_Mesh);
	SAFE_DEL(m_Texture);
	SAFE_DEL(m_Shader);
}

void Image2D::NextImage()
{

}